const { Fun, Comment, Like, Ticket } = require("../model");

// 改
exports.updateFun = async (req, res, next) => {
  try {
    const fun = await Fun.findByIdAndUpdate(req.params.id, req.body)
    if (fun) {
      res.status(200).json({
        code: 200,
        msg: "success",
      });
    } else {
      res.status(200).json({
        code: 500,
        msg: "修改失败",
      });
    }
    
  } catch (error) {
    next(error);
  }
};

// 改某一属性
exports.updateFunParams = async (req, res, next) => {
  try {
    const fun = await Fun.findByIdAndUpdate(req.params.id, {
      $set: req.body
    })
    if (fun) {
      res.status(200).json({
        code: 200,
        msg: "success",
      });
    } else {
      res.status(200).json({
        code: 500,
        msg: "修改失败",
      });
    }
    
  } catch (error) {
    next(error);
  }
};
// 搜索景点
exports.getFun = async (req, res, next) => {
  try {
    const items = await Fun.find();
    let data = []
    for (let i = 0;i< items.length;i++) {
      // 查询评论的点赞信息
      let comments = await Comment.find({
        funId: items[i]._id
      })
      // 查询买票信息
      let tickets = await Ticket.find({
        funId: items[i]._id
      })
      let likes = await Like.find({
        funId: items[i]._id
      })
      data.push({
        funInfo: items[i],
        comments,
        tickets,
        likes
      })
    }
    // 获取fun的评论
    res.status(200).json({
      code: 200,
      data
    });
  } catch (error) {
    next(error);
  }
};
// 通过id查找
exports.getFunById = async (req, res, next) => {
  try {
    const items = await Fun.findById(req.params.id);
    console.log(JSON.stringify(items))
    // 查找fun的likes
    if (!items) {
      res.status(200).json({
        code: 200,
        data: []
      });
    }
    let data = {
      funInfo: items
    }
    // 查询评论的发表用户信息
    let likes = await Like.find({
      funId: items._id
    });
    // 查询买票信息
    let tickets = await Ticket.find({
      funId: items._id
    })
    data.likes = likes
    data.tickets = tickets
    res.status(200).json({
      code: 200,
      data
    });
  } catch (error) {
    next(error);
  }
};
// 增
exports.addFun = async (req, res, next) => {
  try {
    const model = new Fun(req.body);
    await model.save();
    res.status(200).json({
      code: 200,
      msg: "success",
    });
  } catch (error) {
    next(error);
  }
};
// 删
exports.deleteFun = async (req, res, next) => {
  try {
    const rs = await Fun.findByIdAndDelete(req.params.id)
    if (rs) {
      res.status(200).json({
        code: 200,
        msg: '删除成功'
      });
    }
  } catch (error) {
    next(error);
  }
};

